<?php

namespace App\Models\Traits;

use App\Models\Category;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

trait CategoryCacheTrait
{
	public static function sCategoriesCacheKey()
	{
		return "product_categories";
	}
	
	public static function sCacheKey($cid)
	{
		return "product_categorie_{$cid}";
	}
	
	public static function sGetCategories()
	{
		if (Redis::zCard(self::sCategoriesCacheKey()) <= 0) {

			return collect();
		}
		
		$categories = collect();
		$ids = Redis::zRange(self::sCategoriesCacheKey(), 0, -1);
		
		foreach ($ids as $id) {
			$category = Cache::get(self::sCacheKey($id));
			$categories->push($category);
		}
		
		return $categories;
	}
	
	
	/*==================================================================================================================*/
	
	
	public function CacheKey()
	{
		return self::sCacheKey($this->id);
	}
	
	public function cacheFields()
	{
		return [
			'id' => (int)$this->id,
			'parent_id' => (int)$this->parent_id,
			'name' => $this->name,
			'name_mini' => $this->name_mini,
			'image_url' => img_path($this->image_uri),
		];
	}
	
	public function addToCache()
	{
		$data = $this->cacheFields();
		Cache::put($this->cacheKey(), $data);
		
		Redis::zAdd(self::sCategoriesCacheKey(), $this->id, $this->id);
	}
	
	public function delFromCache()
	{
		Cache::forget($this->cacheKey());
		Redis::zRem(self::sCategoriesCacheKey(), $this->id);
	}
}
